/*
 ******************************************************************************
 * Parts of this code sample are licensed under Apache License, Version 2.0   *
 * Copyright (c) 2009, Android Open Handset Alliance. All rights reserved.    *
 *																			  *																			*
 * Except as noted, this code sample is offered under a modified BSD license. *
 * Copyright (C) 2010, Motorola Mobility, Inc. All rights reserved.           *
 * 																			  *
 * For more details, see MOTODEV_Studio_for_Android_LicenseNotices.pdf        * 
 * in your installation folder.                                               *
 ******************************************************************************
 */
package ru.tomsk.autovokzal.db.timetable.provider;

import java.util.*;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.net.*;
import android.text.*;

import ru.tomsk.autovokzal.db.timetable.helper.*;

public class TimetableContentProvider extends ContentProvider {

	private TimeTableHelper dbHelper;
	private static HashMap<String, String> TIMETABLE_PROJECTION_MAP;
	private static final String TABLE_NAME = "timetable";
	private static final String AUTHORITY = "ru.tomsk.autovokzal.db.timetable.provider.timetablecontentprovider";

	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + TABLE_NAME);
	public static final Uri _ID_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase());
	public static final Uri NUMBEROFROUTEID_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/numberofrouteid");
	public static final Uri STARTPOINTID_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/startpointid");
	public static final Uri ENDPOINTID_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/endpointid");
	public static final Uri DEPATURETIME_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/depaturetime");
	public static final Uri DAYOFFOLLOWING_FIELD_CONTENT_URI = Uri
			.parse("content://" + AUTHORITY + "/" + TABLE_NAME.toLowerCase()
					+ "/dayoffollowing");
	public static final Uri PRICE_FIELD_CONTENT_URI = Uri.parse("content://"
			+ AUTHORITY + "/" + TABLE_NAME.toLowerCase() + "/price");

	public static final String DEFAULT_SORT_ORDER = "_id ASC";

	private static final UriMatcher URL_MATCHER;

	private static final int TIMETABLE = 1;
	private static final int TIMETABLE__ID = 2;
	private static final int TIMETABLE_NUMBEROFROUTEID = 3;
	private static final int TIMETABLE_STARTPOINTID = 4;
	private static final int TIMETABLE_ENDPOINTID = 5;
	private static final int TIMETABLE_DEPATURETIME = 6;
	private static final int TIMETABLE_DAYOFFOLLOWING = 7;
	private static final int TIMETABLE_PRICE = 8;

	// Content values keys (using column names)
	public static final String _ID = "_id";
	public static final String NUMBEROFROUTEID = "NumberOfRouteId";
	public static final String STARTPOINTID = "StartPointId";
	public static final String ENDPOINTID = "EndPointId";
	public static final String DEPATURETIME = "DepatureTime";
	public static final String DAYOFFOLLOWING = "DayOfFollowing";
	public static final String PRICE = "Price";

	public boolean onCreate() {
		dbHelper = new TimeTableHelper(getContext());
		return (dbHelper == null) ? false : true;
	}

	public Cursor query(Uri url, String[] projection, String selection,
			String[] selectionArgs, String sort) {
		SQLiteDatabase mDB = dbHelper.getReadableDatabase();
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch (URL_MATCHER.match(url)) {
		case TIMETABLE:
			qb.setTables(TABLE_NAME);
			qb.setProjectionMap(TIMETABLE_PROJECTION_MAP);
			break;
		case TIMETABLE__ID:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("_id=" + url.getPathSegments().get(1));
			break;
		case TIMETABLE_NUMBEROFROUTEID:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("numberofrouteid='" + url.getPathSegments().get(2)
					+ "'");
			break;
		case TIMETABLE_STARTPOINTID:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("startpointid='" + url.getPathSegments().get(2)
					+ "'");
			break;
		case TIMETABLE_ENDPOINTID:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("endpointid='" + url.getPathSegments().get(2) + "'");
			break;
		case TIMETABLE_DEPATURETIME:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("depaturetime='" + url.getPathSegments().get(2)
					+ "'");
			break;
		case TIMETABLE_DAYOFFOLLOWING:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("dayoffollowing='" + url.getPathSegments().get(2)
					+ "'");
			break;
		case TIMETABLE_PRICE:
			qb.setTables(TABLE_NAME);
			qb.appendWhere("price='" + url.getPathSegments().get(2) + "'");
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		String orderBy = "";
		if (TextUtils.isEmpty(sort)) {
			orderBy = DEFAULT_SORT_ORDER;
		} else {
			orderBy = sort;
		}
		Cursor c = qb.query(mDB, projection, selection, selectionArgs, null,
				null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), url);
		return c;
	}

	public String getType(Uri url) {
		switch (URL_MATCHER.match(url)) {
		case TIMETABLE:
			return "vnd.android.cursor.dir/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE__ID:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_NUMBEROFROUTEID:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_STARTPOINTID:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_ENDPOINTID:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_DEPATURETIME:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_DAYOFFOLLOWING:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";
		case TIMETABLE_PRICE:
			return "vnd.android.cursor.item/vnd.ru.tomsk.autovokzal.db.timetable.provider.timetable";

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
	}

	public Uri insert(Uri url, ContentValues initialValues) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		long rowID;
		ContentValues values;
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}
		if (URL_MATCHER.match(url) != TIMETABLE) {
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		rowID = mDB.insert("timetable", "timetable", values);
		if (rowID > 0) {
			Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(uri, null);
			return uri;
		}
		throw new SQLException("Failed to insert row into " + url);
	}

	public int delete(Uri url, String where, String[] whereArgs) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		int count;
		String segment = "";
		switch (URL_MATCHER.match(url)) {
		case TIMETABLE:
			count = mDB.delete(TABLE_NAME, where, whereArgs);
			break;
		case TIMETABLE__ID:
			segment = url.getPathSegments().get(1);
			count = mDB.delete(TABLE_NAME,
					"_id="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_NUMBEROFROUTEID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"numberofrouteid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_STARTPOINTID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"startpointid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_ENDPOINTID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"endpointid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_DEPATURETIME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"depaturetime="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_DAYOFFOLLOWING:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"dayoffollowing="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_PRICE:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.delete(TABLE_NAME,
					"price="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	public int update(Uri url, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase mDB = dbHelper.getWritableDatabase();
		int count;
		String segment = "";
		switch (URL_MATCHER.match(url)) {
		case TIMETABLE:
			count = mDB.update(TABLE_NAME, values, where, whereArgs);
			break;
		case TIMETABLE__ID:
			segment = url.getPathSegments().get(1);
			count = mDB.update(TABLE_NAME, values,
					"_id="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_NUMBEROFROUTEID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"numberofrouteid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_STARTPOINTID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"startpointid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_ENDPOINTID:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"endpointid="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_DEPATURETIME:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"depaturetime="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_DAYOFFOLLOWING:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"dayoffollowing="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		case TIMETABLE_PRICE:
			segment = "'" + url.getPathSegments().get(2) + "'";
			count = mDB.update(TABLE_NAME, values,
					"price="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	static {
		URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase(), TIMETABLE);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/#",
				TIMETABLE__ID);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/numberofrouteid" + "/*", TIMETABLE_NUMBEROFROUTEID);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/startpointid" + "/*", TIMETABLE_STARTPOINTID);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/endpointid"
				+ "/*", TIMETABLE_ENDPOINTID);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/depaturetime" + "/*", TIMETABLE_DEPATURETIME);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase()
				+ "/dayoffollowing" + "/*", TIMETABLE_DAYOFFOLLOWING);
		URL_MATCHER.addURI(AUTHORITY, TABLE_NAME.toLowerCase() + "/price"
				+ "/*", TIMETABLE_PRICE);

		TIMETABLE_PROJECTION_MAP = new HashMap<String, String>();
		TIMETABLE_PROJECTION_MAP.put(_ID, "_id");
		TIMETABLE_PROJECTION_MAP.put(NUMBEROFROUTEID, "numberofrouteid");
		TIMETABLE_PROJECTION_MAP.put(STARTPOINTID, "startpointid");
		TIMETABLE_PROJECTION_MAP.put(ENDPOINTID, "endpointid");
		TIMETABLE_PROJECTION_MAP.put(DEPATURETIME, "depaturetime");
		TIMETABLE_PROJECTION_MAP.put(DAYOFFOLLOWING, "dayoffollowing");
		TIMETABLE_PROJECTION_MAP.put(PRICE, "price");

	}
}
